# pip install baidu-aip -i https://mirrors.aliyun.com/pypi/simple/
# pip install chardet -i https://mirrors.aliyun.com/pypi/simple/
# 导入AipOcr库
from aip import AipOcr

# 设置您的APPID、API Key和Secret Key
# 账号：liqian89
# 密码：Liqian89
APP_ID = "118828045"
API_KEY = "x7NwDiU4WvKv5vKfJAaU7Vq2"
SECRET_KEY = "CJW1j3q4CJT1QhSWKBasJlV4LEUSJWrT"

# 初始化AipOcr对象
client = AipOcr(APP_ID, API_KEY, SECRET_KEY)


def get_file_content(filePath):
    """
    读取图片文件内容
    :param filePath: 图片路径
    :return: 图片的二进制数据
    """
    with open(filePath, "rb") as fp:
        return fp.read()


def ocr_image(image_path):
    """
    调用百度AI OCR接口识别图片中的文字
    :param image_path: 图片路径
    :return: 识别结果
    """
    # 获取图片内容
    image = get_file_content(image_path)

    # 调用通用文字识别（高精度版）
    options = {}
    options["language_type"] = "CHN_ENG"  # 中英文混合识别
    options["detect_direction"] = "true"  # 检测图像朝向
    options["paragraph"] = "true"  # 输出段落信息
    options["probability"] = "true"  # 返回置信度

    result = client.basicAccurate(image, options)
    return result


if __name__ == "__main__":
    image_file_path = "D:/项目/python/文字识别/test.png"  # 替换为实际的图片路径
    result = ocr_image(image_file_path)

    print("识别结果如下：")
    if "words_result" in result:
        for item in result["words_result"]:
            print(item["words"])
    else:
        print("未找到识别结果，请检查图片或API参数。")
